package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result TypeList() {
        String key = CACHE_SHOP_TYPE_KEY + UUID.randomUUID().toString();

        String shopTypeJSON = stringRedisTemplate.opsForValue().get(key);

        List<ShopType> shopLists = null;
        // 判断是否存在 存在则返回
        if(StrUtil.isNotBlank(shopTypeJSON)){
            log.info("shopTypeList exist in  Redis");
            shopLists = JSONUtil.toList(shopTypeJSON, ShopType.class);
            return Result.ok(shopLists);
        }
        //不存在就查数据库
        shopLists = this.query().orderByAsc("sort").list();
        if(shopLists == null){
            log.info("不存在ShopLists");
            return Result.fail("不存在ShopLists");
        }

        log.info("查询到ShopLists");

        //存在就把他添加到Redis缓存里 并返回
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopLists),
                CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return Result.ok(shopLists);
    }
}
